package com.meizu.control;

import com.meizu.entity.User;
import com.meizu.service.UserService;
import com.meizu.utils.BaseServlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 登录的控制层操作类
 * @date 2023/4/18
 **/
@WebServlet("/user")
public class LoginServlet extends BaseServlet {
    UserService us=new UserService ();
    @Override
    public String excute(HttpServletRequest request, HttpServletResponse response) throws Exception {
        session.removeAttribute("uphone");
        session.removeAttribute("user");
        return "f:login";
    }
    /**
     *用户登录
     **/
    public String login(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取用户登录参数
        String uphone=request.getParameter ("uphone");
        String upassword=request.getParameter ("upassword");

        //调用业务层方法
        Integer i=us.Login (uphone,upassword);
        if (i==-1){
            request.setAttribute ("error","账号或密码错误");
            request.setAttribute ("display","block");
            return "f:login";
        }else if (i==0) {
            request.setAttribute ("error", "该账号不可用");
            request.setAttribute ("display","block");
            return "f:login";
        }else {
            User user=us.search (uphone);
            if (user!=null){
                session.setAttribute ("user",user);//所有页面通用，存有UID、账号、密码、加密的手机号
            }
            session.setAttribute ("uphone",uphone);//个人中心使用
            return "r:/index";
        }
    }

    /**
     *用户注册
     */
    public String Register(HttpServletRequest request, HttpServletResponse response) throws Exception {
        session.removeAttribute("errorRegister");
        String uphone=request.getParameter ("uphone");
        String upassword=request.getParameter ("upassword");
        Integer i=0;
        if (upassword!=null && !"".equals(upassword)){
            try{
                i=us.Register (uphone,upassword);
            }catch (Exception ignored){

            }finally {
                if (i>0){
                    return "f:login";
                }else {
                    session.setAttribute("errorRegister",-1);
                    return "f:register";
                }
            }
        }
        return "f:register";
    }
}
